﻿Imports System.ServiceModel.DomainServices.Client
Imports LullabyFullDeCaixa.Web

Partial Public Class DetallGestioUsuaris
    Inherits ChildWindow

#Region "Crear i Destruir"
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub Child_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, True)
    End Sub

    Private Sub DetallGestioUsuaris_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        cboRols.ItemsSource = OpcionsComboRols.GetOpcions
        cboIdiomes.ItemsSource = OpcionsComboIdiomes.Llista

        If Contexte.UsuariActual.IdTipusUsuari <> LullabyFullDeCaixa.EnumTipusUsuari.Administrador Then
            cboRols.IsEnabled = False
            listHostals.IsEnabled = False
            listReports.IsEnabled = False
            btnEliminarUsuari.IsEnabled = False
            btnAfegirUsuari.IsEnabled = False
        End If


        If RiaContext.Current.Authentication.User.Identity.IsAuthenticated = True Then
            Me.Activity.IsActive = True

            AddHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
            Contexte.LoadUsuaris()

            AddHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
            Contexte.LoadHostals()
        End If
    End Sub
#End Region

#Region "Guardar i Cancelar"
    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        EliminarObjectErrors()

        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            If ValidarDades() Then
                LullabyFullDeCaixa.Contexte.DomainContext.SubmitChanges(AddressOf DomainContext_SubmittedChanges, Nothing)
                Activity.IsActive = True
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Function ValidarDades() As Boolean
        Dim Resultat As Boolean = True

        For Each U As Usuari In listUsuaris.Items
            If U.IdTipusUsuari = EnumTipusUsuari.Administrador Then
                While U.UsuariHostals.Count > 0
                    Dim UH As UsuariHostal = U.UsuariHostals(0)
                    Contexte.DomainContext.UsuariHostals.Remove(UH)
                    U.UsuariHostals.Remove(UH)
                End While
            Else
                If U.UsuariHostals.Count = 0 Then
                    Dim ErrorItem As ValidationSummaryItem = New ValidationSummaryItem
                    ErrorItem.ItemType = ValidationSummaryItemType.ObjectError
                    ErrorItem.MessageHeader = StringLibrary.UsuariSensePermis
                    ErrorItem.Message = String.Format(StringLibrary.UsuariSensePermis1, U.Nom)
                    ErrorItem.Context = listUsuaris

                    Me.Validacio.Errors.Add(ErrorItem)
                    Resultat = False
                End If
            End If
        Next

        Return Resultat
    End Function

    Private Sub DomainContext_SubmittedChanges(ByVal s As SubmitOperation)
        Activity.IsActive = False

        If s.HasError Then
            If s.Error.Message.Contains("IX_LullabyUsuariUserNamePassword") Then
                Dim ValidationItem As New ValidationSummaryItem()
                ValidationItem.MessageHeader = StringLibrary.Usuari_Duplicat
                ValidationItem.Message = StringLibrary.UsuariPasswordRepetit
                ValidationItem.ItemType = ValidationSummaryItemType.ObjectError
                Validacio.Errors.Add(ValidationItem)

                s.MarkErrorAsHandled()
            ElseIf s.Error.Message.Contains("REFERENCE") Then
                Dim ValidationItem As New ValidationSummaryItem()
                ValidationItem.MessageHeader = StringLibrary.ImpossibleEliminar
                ValidationItem.Message = StringLibrary.DatosRelacionados
                ValidationItem.ItemType = ValidationSummaryItemType.ObjectError
                Validacio.Errors.Add(ValidationItem)

                s.MarkErrorAsHandled()
            Else
                App.ReportError(StringLibrary.ErrorGuardantDades)
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            LullabyFullDeCaixa.Contexte.DomainContext.RejectChanges()
        End If

        Me.DialogResult = False
    End Sub

    Public Sub EliminarObjectErrors()
        Dim i As Long

        i = 0
        While i < Validacio.Errors.Count
            If Validacio.Errors(i).ItemType = ValidationSummaryItemType.ObjectError Then
                Validacio.Errors.RemoveAt(i)
            Else
                i = i + 1
            End If
        End While
    End Sub
#End Region

#Region "Carregar Dades"
    Private _HostalsCarregats As Boolean = False
    Private _UsuarisCarregats As Boolean = False

    Private Sub UsuarisCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats

        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            listUsuaris.ItemsSource = Contexte.Usuaris
        Else
            listUsuaris.ItemsSource = {Contexte.UsuariActual}
        End If

        _UsuarisCarregats = True
        If _HostalsCarregats And _UsuarisCarregats Then Me.Activity.IsActive = False
    End Sub

    Public Sub HostalsCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats

        _HostalsCarregats = True
        If _HostalsCarregats And _UsuarisCarregats Then Me.Activity.IsActive = False
    End Sub
#End Region

#Region "Creació i eliminació de permisos"
    Private Sub listUsuaris_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        If e.AddedItems.Count = 0 Then
            Me.gridDetall.Visibility = Windows.Visibility.Collapsed
            HostalTePermisConverter.Usuari = Nothing
            ReportTePermisConverter.Usuari = Nothing
            listHostals.ItemsSource = Nothing
            listReports.ItemsSource = Nothing
            Me.btnEliminarUsuari.IsEnabled = False
        Else
            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then Me.btnEliminarUsuari.IsEnabled = True

            Dim UsuariSeleccionat As Usuari = e.AddedItems(0)
            Me.gridDetall.Visibility = Windows.Visibility.Visible

            If UsuariSeleccionat.IdTipusUsuari = EnumTipusUsuari.Administrador Then
                listHostals.Visibility = Windows.Visibility.Collapsed
                lblPermisos.Visibility = Windows.Visibility.Collapsed
            Else
                listHostals.Visibility = Windows.Visibility.Visible
                lblPermisos.Visibility = Windows.Visibility.Visible

            End If

            If UsuariSeleccionat.IdTipusUsuari = EnumTipusUsuari.Manager Then
                listReports.Visibility = Windows.Visibility.Visible
                lblReports.Visibility = Windows.Visibility.Visible
            Else
                listReports.Visibility = Windows.Visibility.Collapsed
                lblReports.Visibility = Windows.Visibility.Collapsed
            End If

            HostalTePermisConverter.Usuari = UsuariSeleccionat
            listHostals.ItemsSource = Contexte.Hostals.OrderBy(Function(f) f.Nom)

            ReportTePermisConverter.Usuari = UsuariSeleccionat
            listReports.ItemsSource = ConfigReportAbstract.ReportList.OrderBy(Function(f) f.NomReport)

        End If
    End Sub

    Private Sub CheckBoxReport_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim chk As CheckBox = DirectCast(sender, CheckBox)
        Dim Report As TipusReport = DirectCast(chk.DataContext, TipusReport)
        Dim Usuari As Usuari = DirectCast(listUsuaris.SelectedItem, Usuari)
        Dim Permis As UsuariReport = (From P As UsuariReport In Usuari.UsuariReports Where P.IdReport = Report.tipusReport).FirstOrDefault

        If Permis Is Nothing Then
            'Hem de crear el permis
            Permis = New UsuariReport() With {.Usuari = Usuari, .IdReport = Report.tipusReport}
        Else
            'Ja tenim el permis, no cal fer res
        End If
    End Sub

    Private Sub CheckBoxReport_Unchecked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim chk As CheckBox = DirectCast(sender, CheckBox)
        Dim Report As TipusReport = DirectCast(chk.DataContext, TipusReport)
        Dim Usuari As Usuari = DirectCast(listUsuaris.SelectedItem, Usuari)
        Dim Permis As UsuariReport = (From P As UsuariReport In Usuari.UsuariReports Where P.IdReport = Report.tipusReport).FirstOrDefault

        If Permis Is Nothing Then
            'No teniem el permis, no cal fer res
        Else
            'Hem d'eliminar el permis
            Contexte.DomainContext.UsuariReports.Remove(Permis)
        End If
    End Sub


    Private Sub CheckBoxHostal_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim chk As CheckBox = DirectCast(sender, CheckBox)
        Dim Hostal As Hostal = DirectCast(chk.DataContext, Hostal)
        Dim Usuari As Usuari = DirectCast(listUsuaris.SelectedItem, Usuari)
        Dim Permis As UsuariHostal = (From P As UsuariHostal In Usuari.UsuariHostals Where P.IdHostal = Hostal.Id).FirstOrDefault

        If Permis Is Nothing Then
            'Hem de crear el permis
            Permis = New UsuariHostal() With {.Usuari = Usuari, .Hostal = Hostal}
        Else
            'Ja tenim el permis, no cal fer res
        End If
    End Sub

    Private Sub CheckBoxHostal_Unchecked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim chk As CheckBox = DirectCast(sender, CheckBox)
        Dim Hostal As Hostal = DirectCast(chk.DataContext, Hostal)
        Dim Usuari As Usuari = DirectCast(listUsuaris.SelectedItem, Usuari)
        Dim Permis As UsuariHostal = (From P As UsuariHostal In Usuari.UsuariHostals Where P.IdHostal = Hostal.Id).FirstOrDefault

        If Permis Is Nothing Then
            'No teniem el permis, no cal fer res
        Else
            'Hem d'eliminar el permis
            Contexte.DomainContext.UsuariHostals.Remove(Permis)
        End If
    End Sub

#End Region

#Region "Boto Eliminar i afegir"

    Private Sub btnEliminarUsuari_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If DirectCast(listUsuaris.SelectedItem, Usuari).Id = LullabyFullDeCaixa.Contexte.UsuariActual.Id Then
            App.ShowMessage(String.Format(StringLibrary.UsuariActiu, LullabyFullDeCaixa.Contexte.UsuariActual.Nom))
        Else
            Dim Usuari As Usuari = DirectCast(listUsuaris.SelectedItem, Usuari)

            For Each Permis As UsuariHostal In Usuari.UsuariHostals
                LullabyFullDeCaixa.Contexte.DomainContext.UsuariHostals.Remove(Permis)
            Next
            LullabyFullDeCaixa.Contexte.DomainContext.Usuaris.Remove(Usuari)

            'Sempre som administradors
            listUsuaris.ItemsSource = Contexte.Usuaris
        End If
    End Sub


    Private Sub btnAfegirUsuari_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim nouUsuari As New LullabyFullDeCaixa.Web.Usuari() With {.Nom = "Default User", .IdTipusUsuari = EnumTipusUsuari.Recepcionista, .Idioma = "es-ES"}
        Contexte.DomainContext.Usuaris.Add(nouUsuari)

        'Sempre som administradors
        listUsuaris.ItemsSource = Contexte.Usuaris

        listUsuaris.SelectedItem = nouUsuari

        txtNom.Focus()
        txtNom.SelectAll()
    End Sub

#End Region

    Private Sub Scroll_SizeChanged(ByVal sender As System.Object, ByVal e As System.Windows.SizeChangedEventArgs)
        Me.Components.MaxHeight = Math.Max(Me.Scroll.ViewportHeight, Me.Components.MinHeight)
        Me.Components.MaxWidth = Math.Max(Me.Scroll.ViewportWidth, Me.Components.MinWidth)
    End Sub

    Private Sub cboRols_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles cboRols.SelectionChanged
        If e.AddedItems.Count = 0 Then Return

        Dim RolSeleccionat As OpcioCombo = e.AddedItems(0)
        Dim Usuari As Usuari = DirectCast(listUsuaris.SelectedItem, Usuari)

        If RolSeleccionat.Id = EnumTipusUsuari.Administrador Then
            listHostals.Visibility = Windows.Visibility.Collapsed
            lblPermisos.Visibility = Windows.Visibility.Collapsed

            While Usuari.UsuariHostals.Count > 0
                'Usuari.UsuariHostals.Remove(Usuari.UsuariHostals(0))
                Contexte.DomainContext.UsuariHostals.Remove(Usuari.UsuariHostals(0))
            End While
        Else
            listHostals.Visibility = Windows.Visibility.Visible
            lblPermisos.Visibility = Windows.Visibility.Visible
        End If

        If RolSeleccionat.Id = EnumTipusUsuari.Manager Then
            listReports.Visibility = Windows.Visibility.Visible
            lblReports.Visibility = Windows.Visibility.Visible
        Else
            listReports.Visibility = Windows.Visibility.Collapsed
            lblReports.Visibility = Windows.Visibility.Collapsed

            While Usuari.UsuariReports.Count > 0
                Contexte.DomainContext.UsuariReports.Remove(Usuari.UsuariReports(0))
            End While
        End If

        'Refresquem les llistes
        listHostals.ItemsSource = Contexte.Hostals.OrderBy(Function(f) f.Nom)
        listReports.ItemsSource = ConfigReportAbstract.ReportList.OrderBy(Function(f) f.NomReport)

    End Sub
End Class

Public Class HostalTePermisConverter
    Implements Data.IValueConverter

    Private Shared _Usuari As Usuari
    Public Shared Property Usuari() As Usuari
        Get
            Return _Usuari
        End Get
        Set(ByVal value As Usuari)
            _Usuari = value
        End Set
    End Property

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If TypeOf (value) Is Hostal AndAlso Usuari IsNot Nothing Then
            Dim Hostal As Hostal = DirectCast(value, Hostal)
            Dim Permis As UsuariHostal = (From P In Hostal.UsuariHostals Where P.IdUsuari = Usuari.Id).FirstOrDefault

            Return Permis IsNot Nothing
        Else
            Return False
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException(StringLibrary.ErrorConvertPermis)
    End Function
End Class

Public Class ReportTePermisConverter
    Implements Data.IValueConverter

    Private Shared _Usuari As Usuari
    Public Shared Property Usuari() As Usuari
        Get
            Return _Usuari
        End Get
        Set(ByVal value As Usuari)
            _Usuari = value
        End Set
    End Property

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If TypeOf (value) Is TipusReport AndAlso Usuari IsNot Nothing Then
            Dim Report As TipusReport = DirectCast(value, TipusReport)
            Dim Permis As UsuariReport = (From P In Usuari.UsuariReports Where P.IdReport = Report.tipusReport).FirstOrDefault

            Return Permis IsNot Nothing
        Else
            Return False
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException(StringLibrary.ErrorConvertPermis)
    End Function
End Class

